<template>
  <div class="app-container">
    <div class="module-box">
      <div class="module-item">
        <div class="module-item-title">
          <span class="tit">基本信息</span>
        </div>
        <div class="form module-item-content form-item-small" style="padding-top:35px;overflow: hidden;">
          <el-form :model="validateForm" :rules="rules" ref="validateForm" :label-position="'top'">
            <el-row :gutter="200">
              <el-col :sm="12" :md="8" :lg="8">
                <!-- <el-form-item label="项目编号：">
                <el-input v-model="validateForm.name" placeholder="项目编号" />
                </el-form-item>-->
                <el-form-item label="项目名称：" prop="name">
                  <el-tooltip effect="dark" :disabled="(validateForm.name == null || validateForm.name == '') ? true : false" :content="validateForm.name">
                    <el-input v-model="validateForm.name" placeholder="请输入项目名称" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="项目类型：" prop="projectTypeId">
                  <el-select v-model="validateForm.projectTypeId" placeholder="--请选择--">
                    <el-option v-for="(item, index) in PROJECT_TYPE" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="项目级别：" prop="level">
                  <el-select v-model="validateForm.level" placeholder="--请选择--">
                    <el-option label="区县级" value="DISTRICT" />
                    <el-option label="市级" value="CITY" />
                  </el-select>
                </el-form-item>
                <el-form-item label="指标使用方向：" prop="projectIndexId">
                  <el-select v-model="validateForm.projectIndexId" placeholder="--请选择--">
                    <el-option v-for="(item, index) in PROJECT_INDEX" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :sm="12" :md="8" :lg="8">
                <el-form-item label="是否涉及土地利用现状变更：" prop="isChange">
                  <el-select v-model="validateForm.isChange" placeholder="--请选择--">
                    <el-option label="是" value="YES" />
                    <el-option label="否" value="NO" />
                  </el-select>
                </el-form-item>
                <el-form-item label="土地利用规划名称：" prop="landUtilizePlanName">
                  <el-tooltip effect="dark" :disabled="(validateForm.landUtilizePlanName == null || validateForm.landUtilizePlanName == '') ? true : false" :content="validateForm.landUtilizePlanName">
                    <el-input v-model="validateForm.landUtilizePlanName" placeholder="请输入土地利用规划名称" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="土地整治规划名称：" prop="landRepairPlanName">
                  <el-tooltip effect="dark" :disabled="(validateForm.landRepairPlanName == null || validateForm.landRepairPlanName == '') ? true : false" :content="validateForm.landRepairPlanName">
                    <el-input v-model="validateForm.landRepairPlanName" placeholder="请输入土地整治规划名称" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="乡镇建设规划名称：" prop="townConstructPlanName">
                  <el-tooltip
                    effect="dark"
                    :disabled="(validateForm.townConstructPlanName == null || validateForm.townConstructPlanName == '') ? true : false"
                    :content="validateForm.townConstructPlanName"
                  >
                    <el-input v-model="validateForm.townConstructPlanName" placeholder="请输入乡镇建设规划名称" />
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :sm="12" :md="8" :lg="8">
                <el-form-item label="所属区县：">
                  <el-tooltip effect="dark" :disabled="(displaySsqx == null || displaySsqx == '') ? true : false" :content="displaySsqx">
                    <el-input v-model="displaySsqx" disabled placeholder="所属区县" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="主要乡镇：">
                  <el-tooltip effect="dark" :disabled="(displayZyxzStr == null || displayZyxzStr == '') ? true : false" :content="displayZyxzStr">
                    <el-input v-model="displayZyxzStr" disabled placeholder="主要乡镇" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="行政村：">
                  <el-tooltip effect="dark" :disabled="(displayXzcStr == null || displayXzcStr == '') ? true : false" :content="displayXzcStr">
                    <el-input v-model="displayXzcStr" disabled placeholder="行政村" />
                  </el-tooltip>
                </el-form-item>
                <el-form-item label="土地使用权面积：">
                  <el-input disabled v-model="displayTdsyqmj" placeholder="土地使用权面积">
                    <span slot="suffix">公顷</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>

      <div class="module-item">
        <div class="module-item-title">
          <span class="tit">选择片块</span>
        </div>
        <div class="module-item-content" style="padding-top:35px;overflow: hidden;">
          <div class="form">
            <el-form :inline="true" label-position="right" label-width="90px">
              <el-form-item label="所在乡镇">
                <el-tooltip effect="dark" :disabled="(displayZyxzStr == null || displayZyxzStr == '') ? true : false" :content="displayZyxzStr">
                  <el-select @change="handleTownChange" v-model="selectedTown" filterable placeholder="--请选择--" clearable>
                    <el-option v-for="(item, index) in townData" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-tooltip>
              </el-form-item>
              <el-form-item label="行政村名称">
                <el-tooltip effect="dark" :disabled="(displayXzcStr == null || displayXzcStr == '') ? true : false" :content="displayXzcStr">
                  <el-select v-model="selectedVillage" placeholder="--请选择--" filterable clearable>
                    <el-option v-for="(item, index) in villageData" :key="index" :label="item.name" :value="item.id" />
                  </el-select>
                </el-tooltip>
              </el-form-item>
              <el-form-item>
                <el-button @click="handleListQuery" type="primary">查询</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="pkSelectedData" highlight-current-row>
            <el-table-column prop="applicantName" label="权利人"></el-table-column>
            <el-table-column label="乡镇名称">
              <template slot-scope="scope">{{ scope.row.town.name }}</template>
            </el-table-column>
            <el-table-column label="行政村名称">
              <template slot-scope="scope">{{ scope.row.village.name }}</template>
            </el-table-column>
            <el-table-column prop="address" label="通讯地址"></el-table-column>
            <el-table-column prop="landArea" label="使用权面积（㎡）"></el-table-column>
            <el-table-column label="片块编号" width="200px">
              <template slot-scope="scope">
                <span>片块</span>
                <el-input type="number" style="width: 60px;" v-model="scope.row.villageIndex" placeholder="片块" />
                <span>-</span>
                <el-input type="number" style="width: 60px;" v-model="scope.row.landIndex" placeholder="片块" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="handleRemovePk(scope.$index)" type="text">移除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- <div class="pagination-container">
            <el-pagination :page-size="2" layout="prev, pager, next, jumper" :total="pkSelectedData.length"></el-pagination>
          </div>-->
        </div>
      </div>

      <div class="submit-box">
        <el-button @click="handleSubmit" type="primary">提交</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </div>

    <el-dialog :close-on-click-modal="false" title="选择片块" :visible.sync="pkDialog">
      <div style="overflow: hidden;">
        <el-table @selection-change="handleSelectionChange" v-loading="listLoading" :data="list" element-loading-text="加载中" highlight-current-row>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="obligeeName" label="权利人"></el-table-column>
          <el-table-column label="乡镇名称">
            <template slot-scope="scope">{{ scope.row.town.name }}</template>
          </el-table-column>
          <el-table-column label="行政村名称">
            <template slot-scope="scope">{{ scope.row.village.name }}</template>
          </el-table-column>
          <el-table-column prop="address" label="通讯地址"></el-table-column>
          <el-table-column prop="landArea" label="使用权面积（㎡）"></el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            :current-page="listQuery.page"
            @size-change="handleSizeChange"
            @current-change="changePage"
            :page-size="listQuery.size"
            layout="prev, pager, next, jumper, sizes"
            :total="total"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="pkDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleAddPk">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDicData, getTownData, getVillageData, getListLandByRegionId, add, calculateArea,getProjectDetail,updateProject } from "@/api/project/xmkgh/xmprezz";

export default {
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        size: 10,
        regionId: null,
        selectedLand: null
      },
      validateForm: {
        name: null,
        level: [],
        projectTypeId: null,
        projectIndexId: null,
        isChange: [],
        landUtilizePlanName: null,
        landRepairPlanName: null,
        townConstructPlanName: null,
        projectLandVos: [],
        districtId:null,
        townId:null,
        landArea:null,
        cityId:null,
      },
      rules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        level: [{ required: true, message: "请选择项目级别", trigger: "blur" }],
        projectTypeId: [{ required: true, message: "请选择项目类型", trigger: "blur" }],
        projectIndexId: [{ required: true, message: "请选择指标使用方向", trigger: "blur" }],
        isChange: [{ required: true, message: "请选择是否涉及土地利用现状变更", trigger: "blur" }],
        landUtilizePlanName: [{ required: true, message: "请输入土地利用规划名称", trigger: "blur" }],
        landRepairPlanName: [{ required: true, message: "请输入土地整治规划名称", trigger: "blur" }],
        townConstructPlanName: [{ required: true, message: "请输入乡镇建设规划名称", trigger: "blur" }]
      },
      PROJECT_INDEX: [],
      PROJECT_TYPE: [],

      displaySsqx: null,
      displayXzc: null,
      displayZyxz: null,
      displaySsqxStr: null,
      displayXzcStr: null,
      displayZyxzStr: null,
      displayTdsyqmj: null,

      townData: [],
      selectedTown: null,
      villageData: [],
      selectedVillage: null,

      pkDialog: false,
      pkAddData: [],
      pkSelectedData: [],
      projectId:null,
      villageIndexData:0,
    };
  },
  watch: {
    pkSelectedData(newVal, oldVal) {
      let landIdArr = [];
      this.displayTdsyqmj = null;
      newVal.forEach(item => {
        landIdArr.push(item.id);
        // this.displayTdsyqmj += item.landArea;
      });
      this.countArea(landIdArr);
      // 计算面积
      this.listQuery.selectedLand = landIdArr.join(",");
    }
  },
  created() {
    this.projectId=this.$route.query.id
    this.getDicData();
    this.getTownData();
    this.getDetail()
  },
  methods: {
    //获取项目详情
    getDetail(){
      var data={
        projectId:this.projectId
      }
      getProjectDetail(data).then(res=>{
        console.log(res,"我是详情")
        this.pkSelectedData=JSON.parse(res.data.pkSelectedData)
        console.log(this.pkSelectedData,"this.pkSelectedDatathis.pkSelectedDatathis.pkSelectedDatathis.pkSelectedDatathis.pkSelectedData")
        this.validateForm.projectTypeId = res.data.projectType.id
        this.validateForm.level = res.data.levelDto.code
        this.validateForm.projectIndexId = res.data.projectIndex.id
        this.validateForm.isChange = res.data.isChangeDto.code

        this.validateForm.landUtilizePlanName = res.data.landUtilizePlanName
        this.validateForm.landRepairPlanName = res.data.landRepairPlanName
        this.validateForm.townConstructPlanName = res.data.townConstructPlanName

        this.displaySsqx = res.data.districts.join(",")
        this.displayZyxzStr = res.data.mainTowns.join(",")
        this.displayXzcStr = res.data.villages.join(",")

        this.validateForm.districtId = res.data.districtId
        this.validateForm.townId = res.data.townId
        this.validateForm.cityId = res.data.cityId

        this.validateForm.name = res.data.name
      })
    },
    countArea(arr) {
      var data={
        landIdList:arr.join(",")
      }
      calculateArea(data).then(res => {
        this.displayTdsyqmj = res.data;
        this.validateForm.landArea = res.data;
      });
    },
    changePage(page) {
      this.listQuery.page = page;
      this.getListLandByRegionId();
    },
    handleSizeChange(size) {
      this.listQuery.size = size;
      this.getListLandByRegionId();
    },
    handleSelectionChange(arr) {
      this.pkAddData = arr;
    },
    handleAddPk() {
      if (this.pkAddData.length == 0) {
        this.$alert("请至少选择一个片块", "提示");
        return;
      }
      this.pkSelectedData = this.pkSelectedData.concat(this.handlePkSelectedData(this.pkAddData))
      
      this.handleResetName(this.pkSelectedData)
      console.log(this.pkSelectedData,"this.pkSelectedData")
      this.pkDialog = false;
      
    },
    handlePkSelectedData(data) {
      console.log(data,"datadatadata")
      if(data&&data.length>0){
        let arr = data;
        let returnArr = [];
        let obj = {};
        let needData = [];
        arr.forEach(item => {
          if (!obj[item.district.name]) {
            obj[item.district.name] = {};
          }
        });
        arr.forEach(item => {
          if (!obj[item.district.name][item.town.name]) {
            obj[item.district.name][item.town.name] = {};
          }
        });
        arr.forEach(item => {
          if (!obj[item.district.name][item.town.name][item.village.name]) {
            obj[item.district.name][item.town.name][item.village.name] = [];
          }
        });
        arr.forEach(item => {
          obj[item.district.name][item.town.name][item.village.name].push(item);
          needData.push(item)
        });
        console.log(obj,"objobjobjobj")
        console.log(needData,"needDataneedDataneedDataneedData")
        let _districtArr = [];
        let _townArr = [];
        let _villageArr = [];
        // let _townIndex = 0;
        let _villageIndex = this.villageIndexData;
        let _pkIndex = 0;
        for (const district in obj) {
          _districtArr.push(district);
          for (const town in obj[district]) {
            _townArr.push(town);
            for (const village in obj[district][town]) {
              _villageArr.push(village);
              _pkIndex = 0;
              _villageIndex++;
              for (const pk in obj[district][town][village]) {
                _pkIndex++;
                obj[district][town][village][pk].villageIndex = _villageIndex;
                obj[district][town][village][pk].landIndex = _pkIndex;
                returnArr.push(obj[district][town][village][pk]);
              }
            }
          }
        }
        this.villageIndexData = _villageIndex
        return returnArr;
      }else{

        var nullArr=[]
        return nullArr;
      }
      
    },
    handleResetName(data) {
      if(data&&data.length>0){
        console.log(data,"datadatadata")
        let arr = data;
        let returnArr = [];
        let obj = {};
        let needData = [];
        arr.forEach(item => {
          if (!obj[item.district.name]) {
            obj[item.district.name] = {};
          }
        });
        arr.forEach(item => {
          if (!obj[item.district.name][item.town.name]) {
            obj[item.district.name][item.town.name] = {};
          }
        });
        arr.forEach(item => {
          if (!obj[item.district.name][item.town.name][item.village.name]) {
            obj[item.district.name][item.town.name][item.village.name] = [];
          }
        });
        arr.forEach(item => {
          obj[item.district.name][item.town.name][item.village.name].push(item);
          needData.push(item)
        });
        console.log(obj,"objobjobjobj")
        console.log(needData,"needDataneedDataneedDataneedData")
        let _districtArr = [];
        let _townArr = [];
        let _villageArr = [];
        // let _townIndex = 0;
        let _villageIndex = 0;
        let _pkIndex = 0;
        for (const district in obj) {
          _districtArr.push(district);
          for (const town in obj[district]) {
            _townArr.push(town);
            for (const village in obj[district][town]) {
              _villageArr.push(village);
              for (const pk in obj[district][town][village]) {
                returnArr.push(obj[district][town][village][pk]);
              }
            }
          }
        }

        this.displaySsqx = _districtArr.join(",");

        this.displayZyxzStr = _townArr.join(",");
        this.displayXzcStr = _villageArr.join(",");
        console.log(_districtArr,_townArr,_villageArr)
        var displaySsqxDisplay=''
        var displayZyxzStrDisplay=''
        var displayXzcStrDisplay=''
        var displaySsqxDisplay1=''
        var displayZyxzStrDisplay1=''
        var displayXzcStrDisplay1=''
        if (_townArr.length > 1) {
          displayZyxzStrDisplay = _townArr[0] + `等${_townArr.length}个镇农村建设用地复垦项目`;
          displayZyxzStrDisplay1 = _townArr[0] + `等${_townArr.length}个镇农村`;
          this.displayZyxz = _townArr[0] + `等${_townArr.length}个镇`;
          this.validateForm.name = this.displaySsqx + displayZyxzStrDisplay;
        } else {
          this.displayZyxz = _townArr[0] + `等${_townArr.length}个镇`

          displayZyxzStrDisplay = _townArr[0]
          
          if (_villageArr.length > 1) {
            displayXzcStrDisplay = _villageArr[0] + `等${_villageArr.length}个村农村建设用地复垦项目`;
            displayXzcStrDisplay1 = _villageArr[0] + `等${_villageArr.length}个村农村`;
            this.displayXzc = _villageArr[0] + `等${_villageArr.length}个村`;
            

            this.validateForm.name = this.displaySsqx + displayZyxzStrDisplay + displayXzcStrDisplay;
          } else {
            displayXzcStrDisplay = _villageArr[0] + `等1个村农村建设用地复垦项目`;
            displayXzcStrDisplay1 = _villageArr[0] + `等1个村农村`;
            this.displayXzc = _villageArr[0] + `等1个村`;

            this.validateForm.name = this.displaySsqx + displayZyxzStrDisplay + displayXzcStrDisplay;
          }
        }
        this.validateForm.landUtilizePlanName = this.displaySsqx + displayZyxzStrDisplay1 + displayXzcStrDisplay1 + "土地利用规划";
        this.validateForm.landRepairPlanName = this.displaySsqx + displayZyxzStrDisplay1 + displayXzcStrDisplay1 + "土地整治规划";
        this.validateForm.townConstructPlanName = this.displaySsqx + displayZyxzStrDisplay1 + displayXzcStrDisplay1 + "乡镇建设规划";

        let _townIds = [];
        let _districtIds = [];
        let _cityIds = [];

        needData.forEach(v=>{
          _townIds.push(v.town.id)
          _cityIds.push(v.city.id)
          _districtIds.push(v.district.id)
        })

        var array1=this.unique(_townIds)
        var array2=this.unique(_districtIds)
        var array3=this.unique(_cityIds)

        this.validateForm.districtId=array2.join(",");
        this.validateForm.townId=array1.join(",");
        this.validateForm.cityId=array3.join(",");

        // console.log(this.validateForm.districtId,"区县ID")
        // console.log(this.validateForm.townId,"乡镇ID")
        // console.log(this.validateForm.cityId,"城市ID")
      }else{
        this.validateForm.districtId=null;
        this.validateForm.townId=null;
        this.validateForm.cityId=null;
        this.validateForm.landUtilizePlanName = null;
        this.validateForm.landRepairPlanName = null;
        this.validateForm.townConstructPlanName = null;
        this.validateForm.name = null;
        this.displaySsqx = null;
        this.displayZyxzStr = null;
        this.displayXzcStr = null;
        this.displayXzc = null;
      }
      
    },
    unique (arr) {
      return Array.from(new Set(arr))
    },
    handleRemovePk(index) {
      this.pkSelectedData.splice(index, 1);
      // this.pkSelectedData = this.handlePkSelectedData(this.pkSelectedData);
      // this.pkSelectedData = this.pkSelectedData.concat(
      //   this.handlePkSelectedData(this.pkAddData)
      // );

      this.handleResetName(this.pkSelectedData);
    },
    handleListQuery() {
      if (this.selectedTown == null || this.selectedTown == "") {
        this.$alert("请选择所在乡镇", "提示");
        return;
      }
      if (this.selectedVillage == null || this.selectedVillage == "") {
        this.listQuery.regionId = this.selectedTown;
      } else {
        this.listQuery.regionId = this.selectedVillage;
      }
      this.pkDialog = true;
      this.changePage(1);
    },
    getListLandByRegionId() {
      this.listLoading = true;
      getListLandByRegionId(this.listQuery)
        .then(res => {
          this.listLoading = false;
          res.data.rows.forEach(item => {
            item["villageIndex"] = null;
            item["landIndex"] = null;
          });
          this.list = res.data.rows;
          this.total = res.data.total;
        })
        .catch(err => {
          this.listLoading = false;
        });
    },
    getDicData() {
      const that = this;
      let arr = ["PROJECT_INDEX", "PROJECT_TYPE"];
      arr.forEach((item, index) => {
        getDicData({
          dictionaryType: item
        }).then(res => {
          that[item] = res.data;
        });
      });
    },
    getTownData() {
      getTownData().then(res => {
        this.townData = res.data;
      });
    },
    getVillageData() {
      if (this.selectedTown == null || this.selectedTown == "") {
        this.selectedVillage = null;
        this.villageData = [];
        return;
      }
      getVillageData({
        parentId: this.selectedTown
      }).then(res => {
        this.villageData = res.data;
      });
    },
    handleTownChange() {
      this.selectedVillage = "";

      this.getVillageData();
    },
    handleSubmit() {
      this.$refs["validateForm"].validate(valid => {
        if (valid) {
          if (this.pkSelectedData.length <= 0) {
            this.$alert("至少添加一个片块", "提示");
            return;
          }
          this.validateForm.projectLandVos = [];
          this.pkSelectedData.forEach((item, index) => {
            let obj = {
              landId: item.id,
              villageIndex: item.villageIndex,
              landIndex: item.landIndex,
              landNameIndex: index
            };
            this.validateForm.projectLandVos.push(obj);
          });
          this.validateForm["id"]=this.projectId
          this.validateForm["pkSelectedData"]=JSON.stringify(this.pkSelectedData)  
          this.validateForm["pkAddData"]='' 
          updateProject(this.validateForm).then(res => {
            this.$alert("编辑成功", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                this.$router.push({ path: "/xmkgh/xmprezz/list" });
              }
            });
          });
        } else {
          this.$alert("还有未填写的信息", "提示");
          return;
        }
      });
    },
    handleCancel() {
      this.$confirm("此操作将返回上一页, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$router.push({ path: "/xmkgh/xmprezz/list" });
        })
        .catch(() => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.pkInput /deep/ input::-webkit-outer-spin-button,
.pkInput /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}
.pkInput /deep/ input[type="number"]{
    -moz-appearance: textfield;
}
.module-item {
  width: 100%;
  background-color: #fff;
}

.module-item-title {
  width: 100%;
  background: #f8f8f8;
  height: 50px;
  border: 1px solid #efefef;
  overflow: hidden;
  font-size: 18px;
  color: #333;
  font-weight: bold;
  text-indent: 20px;
  line-height: 50px;
}

.module-item-content {
  width: 100%;
  border: 1px solid #ebebeb;
  border-top: none;
  padding: 30px;
  padding-top: 0;
  box-sizing: border-box;
}

.form {
  // .el-input {
  //   width: 200px;
  // }
  /deep/ .el-select {
    width: 100%;
  }

  /deep/ .el-form-item {
    margin-bottom: 30px;
  }
}

.submit-box {
  text-align: left;
  margin-top: 20px;
}
</style>
 